﻿<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ExampleWebRole._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <style type="text/css">
        html, body {
	        height: 100%;
	        overflow: auto;
        }
        body {
	        padding: 0;
	        margin: 0;
	        font-size:10px;
        }
        #silverlightControlHost {
	        height: 100%;
	        text-align:left;
        }
    </style>
    <link rel="Stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript">
        function onSilverlightError(sender, args) {
            var appSource = "";
            if (sender != null && sender != 0) {
                appSource = sender.getHost().Source;
            }

            var errorType = args.ErrorType;
            var iErrorCode = args.ErrorCode;

            if (errorType == "ImageError" || errorType == "MediaError") {
                return;
            }

            var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

            errMsg += "Code: " + iErrorCode + "    \n";
            errMsg += "Category: " + errorType + "       \n";
            errMsg += "Message: " + args.ErrorMessage + "     \n";

            if (errorType == "ParserError") {
                errMsg += "File: " + args.xamlFile + "     \n";
                errMsg += "Line: " + args.lineNumber + "     \n";
                errMsg += "Position: " + args.charPosition + "     \n";
            }
            else if (errorType == "RuntimeError") {
                if (args.lineNumber != 0) {
                    errMsg += "Line: " + args.lineNumber + "     \n";
                    errMsg += "Position: " + args.charPosition + "     \n";
                }
                errMsg += "MethodName: " + args.methodName + "     \n";
            }

            throw new Error(errMsg);
        }
    </script>

    <script type="text/javascript">
        function FileListEmptyEvent() {
            $('#FileList').fadeOut(400, function () {
                $('#FileList').html('No files selected for upload').fadeIn();
            });
            $('#ClearFileList').attr('disabled', true);
            $('#UploadFiles').attr('disabled', true);
            $('#TotalProgress').html('').fadeOut();
            $('#UploadFinished').html('').fadeOut();
        }

        var plugin = document.getElementById("SlPlugin");

        function RemoveFilesFromList() {
            var files = plugin.Content.Files;

            $('#FileList').children().each(function () {
                var child = $(this);
                for (var i = 0; i < files.FileList.length; i++)
                    if (child.attr('id') == 'file' + files.FileList[i].Id) return;
                child.fadeOut();
            });
        }

        function UpdateProgressBars() {
            var files = plugin.Content.Files;
            for (var i = 0; i < files.FileList.length; i++) {
                var id = files.FileList[i].Id;
                $('#file' + id + 'progress').progressbar({ value: files.FileList[i].Percentage });

                $('#file' + id + 'bytesUploaded').html(
                        Math.floor(files.FileList[i].BytesUploaded / 1024)
                        + '/'
                        + Math.floor(files.FileList[i].FileSize / 1024)
                        + ' Kb ['
                        + files.FileList[i].Percentage
                        + '%] - '
                        + files.FileList[i].StateString
                        );
            }
        }

        function AddNewFilesToList() {
            var files = plugin.Content.Files;
            for (var i = 0; i < files.FileList.length; i++)
                if (!$('#file' + files.FileList[i].Id).length) {
                    var id = files.FileList[i].Id;
                    $('#FileList').append(
                                '<div style="clear:both" id="file' + id + '">'
                                + ' <div style="float:left" id="file' + id + 'innerRegion">'
                                + '  <div style="float:left;margin-right:1em">' + files.FileList[i].FileName + ' </div>'
                                + '  <div style="float:left;height:1em;width:20em" id="file' + id + 'progress"></div>'
                                + '  <div style="float:left;position:relative;left:-20em;width:20em;text-align:center" id="file' + id + 'bytesUploaded"></div>'
                                + ' </div>'
                                + ' <button style="float:left;width:1em;height:1em;z-index:1;left:-20em" id="stopFileUpload' + id + '" type="button"></button>'
                                + '</div>');

                    $('#stopFileUpload' + id).button({
                        icons: {
                            primary: "ui-icon-circle-close"
                        },
                        text: false
                    }).click(function () {
                        plugin.Content.MainPage.CancelUpload($(this).attr('_id'));
                    }).attr('_id', id);
                }
        }

        function UpdateDynamicContent() {
            UpdateProgressBars();
            UpdateControlsToCurrentState();
        }

        function RefreshFileList() {
            RemoveFilesFromList();
            AddNewFilesToList();
            UpdateDynamicContent();
        }

        function UpdateControlsToCurrentState() {
            var files = plugin.Content.Files;
            $('#ClearFileList').button({ disabled: files.FileList.length == 0 });
            $('#UploadFiles').button({ disabled: files.FileList.length == 0 });

            for (var i = 0; i < files.FileList.length; i++)
                $('#stopFileUpload' + files.FileList[i].Id).button({
                    disabled: (files.FileList[i].StateString == "Finished" || files.FileList[i].StateString == "Error")
                });
        }

        function CollectionChanged() {
            var files = plugin.Content.Files;
            if (files != undefined && files.FileList.length > 0) RefreshFileList();
        }

        function TotalPercentageChangedEvent(percentage, millisecondsLeft) {
            if (percentage > 0) {
                $('#TotalProgress').html('Total progress percentage: ' + percentage + '%'
                            + ', remaining time:' + millisecondsLeft).fadeIn();
            }
            UpdateDynamicContent();

        }

        function AllFilesFinishedEvent(totalTimeTakenMilliseconds, fileCount) {
            $('#UploadFinished').html('All '
                + fileCount
                + ' files have been uploaded in '
                + totalTimeTakenMilliseconds + ' milliseconds.').fadeIn();

            UpdateProgressBars();
        }

        $(document).ready(function () {
            var containerUrl;
            plugin = document.getElementById("SlPlugin");
            // Get the container to upload to
            $.ajax({
                url: '/Interfaces/UploadService.svc/GetUploadUrl',
                success: function (result) {
                    var parsedResult = $.parseJSON(result);
                    containerUrl = parsedResult;
                }
            });

            $('#UploadFiles').click(function () {
                plugin.Content.MainPage.UploadFiles(containerUrl);
            }).button({
                icons: {
                    primary: "ui-icon-arrowreturnthick-1-n"
                }
            });

            $('#ClearFileList').click(function () {
                plugin.Content.MainPage.ClearList();
            }).button({
                icons: {
                    primary: "ui-icon-trash"
                }
            });

            CollectionChanged();

        });
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Example of how to use the Azure Silverlight File Uploader
    </h2>
    <p>
        Please not that this demo page drag'n dropping files will not work if you run Internet Explorer as an administrator.
    </p>
    <p>
        In the development environment the Azure Blob Storage is not located at the root directory, and we need to add a clientaccesspolicy.xml
        file to the root. When developing we counter this problem by installing and running Fiddler. You also have to add the following Fiddler rule at the bottom of OnBeforeRequest():
        
		// Windows Azure Blob rules<br/>
		if (oSession.host == "app.dev.com:10000") { oSession.host = "127.0.0.1:10000"; }<br/>
		if (oSession.url == "127.0.0.1:10000/clientaccesspolicy.xml") { oSession.url = "127.0.0.1:10000/devstoreaccount1/clientaccesspolicy.xml"; }<br/>

    </p>
    <div  class="ui-widget ui-widget-content ui-helper-clearfix ui-widget-border-all">

        <div id="ChooseFiles" type="button" style="clear:both;font-size:large">Upload files to the Azure Blob Storage</div>
        <label for="FileList">File list:</label>
        <div id="FileList" style="clear:both;overflow:visible"></div>
        <div id="TotalProgress" style="clear:both"></div>
        <div style="clear:both;height:1em"></div>

        <div id="silverlightControlHost" style="float:left;margin:-0.5em 0.5em 0 0">
            <object id="SlPlugin" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="32px" height="40px">
		        <param name="source" value="ClientBin/AzureSilverlightFileUploaderPlugIn.xap"/>
		        <param name="onError" value="onSilverlightError" />
		        <param name="background" value="white" />
		        <param name="minRuntimeVersion" value="4.0.50826.0" />
		        <param name="autoUpgrade" value="true" />
                <param name="initParams" value="MaxFileSizeKB=10000000,MaxUploads=10,AllowMultipleFileUpload=true,CollectionChanged_event=CollectionChanged,TotalPercentageChanged_event=TotalPercentageChangedEvent,AllFilesFinished_event=AllFilesFinishedEvent,FileListEmpty_event=FileListEmptyEvent" />
		        <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
 			        <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
		        </a>
	        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
        </div>
        <div style="clear:both;height:1em"></div>
        <button id="UploadFiles" type="button">Upload</button>
        <button id="ClearFileList" type="button">Clear</button>

        <div id="UploadFinished"></div>
    </div>

</asp:Content>
